<template>
  <div>
    <div :id="echarts" :style="styles"></div>
  </div>
</template>

<script>
import echarts from 'echarts';

export default {
  name: "echarts-new",
  props: {
    styles: {
      type: Object,
      default: () => ({
        height: '400px',
        width: '100%'
      })
    },
    optionData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      myChart: null,
      chartId: `echarts-${Date.now()}`
    }
  },
  computed: {
    echarts() {
      return this.chartId;
    }
  },
  watch: {
    optionData: {
      handler(newVal, oldVal) {
        if (newVal) {
          this.handleSetVisitChart();
        }
      },
      deep: true
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart();
      window.addEventListener('resize', this.wsFunc);
    })
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.wsFunc);
    if (!this.myChart) {
      return;
    }
    this.myChart.dispose();
    this.myChart = null;
  },
  methods: {
    wsFunc() {
      if (this.myChart) {
        this.myChart.resize();
      }
    },
    initChart() {
      const dom = document.getElementById(this.chartId);
      if (!dom) {
        console.error('找不到图表容器元素');
        return;
      }
      this.myChart = echarts.init(dom);
      if (this.optionData) {
        this.myChart.setOption(this.optionData, true);
      }
    },
    handleSetVisitChart() {
      if (!this.optionData) {
        return;
      }
      if (!this.myChart) {
        this.initChart();
        return;
      }
      this.myChart.setOption(this.optionData, true);
    }
  }
}
</script>

<style scoped lang="scss">

</style>
